package com.fingard.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 通配符(*)组合遍历算法
 *
 * @author cruise
 * @version 2017-10-19 14:50:33
 */
public class MatchHelper {
    private static ArrayList<Integer> tmpArr = new ArrayList<Integer>();

    /**
     * 通配符匹配
     *
     * @param array 字符串数组
     */
    public static void printWildcardMatch(String[] array) {
        for (int i = 0; i < array.length; i++) {
            combineArray(0, i, array);
        }

        String[] newArray = new String[array.length];
        System.arraycopy(array, 0, newArray, 0, array.length);

        for (int j = 0; j < newArray.length; j++) {
            newArray[j] = "*";
        }
        printFormatArray(newArray);
    }

    /**
     * 组合数遍历
     *
     * @param index 遍历起始下标
     * @param num   几个*的所有可能组合
     * @param arr   字符串数组
     */
    public static void combineArray(int index, int num, String[] arr) {
        if (num == 0) {
            printFormatArray(arr);
        } else if (num == 1) {
            for (int i = index; i < arr.length; i++) {
                tmpArr.add(i);

                List<Integer> list = new ArrayList<Integer>();

                Iterator<Integer> it = tmpArr.listIterator();
                while (it.hasNext()) {
                    list.add(it.next());
                }

                String[] str = new String[arr.length];
                System.arraycopy(arr, 0, str, 0, arr.length);

                Iterator<Integer> iterator = tmpArr.listIterator();
                while (iterator.hasNext()) {
                    str[iterator.next()] = "*";
                }

                printFormatArray(str);

                tmpArr.remove((Object) i);
            }
        } else if (num > 1) {
            for (int i = index; i <= arr.length - num; i++) {
                tmpArr.add(i);
                combineArray(i + 1, num - 1, arr);
                tmpArr.remove((Object) i);
            }
        } else {
            return;
        }
    }

    /**
     * 数组格式化输出
     *
     * @param array 字符串数组
     */
    public static void printFormatArray(String[] array) {
        String arrayStr = "";

        for (int i = 0; i < array.length; i++) {
            if (arrayStr.length() > 0) {
                arrayStr += "、";
            }
            arrayStr += array[i];
        }
        arrayStr += ";";

        System.out.println(arrayStr);
    }
}
